//
//  TSFileManagerTool.swift
//  TSLiveWallpaper
//
//  Created by 100Years on 2024/12/26.
//

public class TSFileManagerTool {

    /// 获取沙盒 Documents 目录路径
    public static var documentsDirectory: URL {
        return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    }

    /// 获取沙盒 Cache 目录路径
    public static var cacheDirectory: URL {
        return FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
    }

    /// 获取沙盒 Temporary 目录路径
    public static var temporaryDirectory: URL {
        return FileManager.default.temporaryDirectory
    }

    public  static func copyFileWithOverwrite(from sourceURL: URL, to targetURL: URL) {
        let fileManager = FileManager.default
        do {
            removeItem(from: targetURL)
            checkFolderAndCreate(from: targetURL)
            try fileManager.copyItem(at: sourceURL, to: targetURL)
            debugPrint("文件复制成功！")
        } catch {
            debugPrint("文件复制失败: \(error.localizedDescription)")
        }
    }
    
    public static func removeItem(from sourceURL: URL) {
        let fileManager = FileManager.default
        do {
            // 如果目标路径存在同名文件，先删除旧文件
            if fileManager.fileExists(atPath: sourceURL.path) {
                try fileManager.removeItem(at: sourceURL)
            }
            debugPrint("文件删除成功！")
        } catch {
            debugPrint("文件删除失败: \(error.localizedDescription)")
        }
    }
    
    /// 移动文件的方法（自动创建目标文件夹）
    /// - Parameters:
    ///   - sourceURL: 文件的源 URL
    ///   - destinationURL: 目标 URL
    /// - Throws: 如果移动失败，会抛出错误
    public static func moveFile(from sourceURL: URL, to destinationURL: URL) {
        let fileManager = FileManager.default
        
        // 检查源文件是否存在
        guard fileManager.fileExists(atPath: sourceURL.path) else {
            let error = NSError(domain: "FileMoveError", code: 404, userInfo: [NSLocalizedDescriptionKey: "源文件不存在"])
            debugPrint(error)
            return
        }
        
        // 获取目标文件夹的路径
        let destinationDirectory = destinationURL.deletingLastPathComponent()
        do {
            // 如果目标文件夹不存在，创建文件夹
            if !fileManager.fileExists(atPath: destinationDirectory.path) {
                try fileManager.createDirectory(at: destinationDirectory, withIntermediateDirectories: true, attributes: nil)
            }
            
            // 检查目标路径是否已经存在文件
            if fileManager.fileExists(atPath: destinationURL.path) {
                // 如果需要覆盖，可以选择先删除目标文件
                try fileManager.removeItem(at: destinationURL)
            }
            
            // 尝试移动文件
            try fileManager.moveItem(at: sourceURL, to: destinationURL)
        } catch {
            debugPrint("尝试移动文件失败: \(error.localizedDescription)")
        }
    }
    
    public static func getFileName(from url: URL, includeExtension: Bool = true) -> String {
        if includeExtension {
            return url.lastPathComponent
        } else {
            return url.deletingPathExtension().lastPathComponent
        }
    }
    
    public static func checkFolderAndCreate(from destinationURL: URL){
        let fileManager = FileManager.default
        let destinationDirectory = destinationURL.deletingLastPathComponent()
        // 如果目标文件夹不存在，创建文件夹
        if !fileManager.fileExists(atPath: destinationDirectory.path) {
            do {
                try fileManager.createDirectory(at: destinationDirectory, withIntermediateDirectories: true, attributes: nil)
            } catch {
                debugPrint("尝试创建文件夹失败: \(error.localizedDescription)")
            }
        }
    }

    public static func hasContents(atPath path: String) -> Bool {
        let fileManager = FileManager.default
        
        do {
            let contents = try fileManager.contentsOfDirectory(atPath: path)
            return !contents.isEmpty
        } catch {
            print("检查目录内容失败: \(error.localizedDescription)")
            return false
        }
    }
    
    // MARK: - 文件操作方法

    /// 检查文件或文件夹是否存在
    public static func fileExists(at url: URL) -> Bool {
        return FileManager.default.fileExists(atPath: url.path)
    }

    /// 创建文件夹
    public static func createDirectory(at url: URL) throws {
        if !fileExists(at: url) {
            try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil)
        }
    }
    
    //获取缓存目录下文件夹路径
    public static func getCacheSubPath(at url: URL) ->String? {
        let array = url.path.components(separatedBy:"/Caches/")
        let cashFilePath = array.last
        return cashFilePath
    }
    
}

public extension String {
    
    public var isCachesPath:Bool{
        return self.contains("/Caches/")
    }
    
    public var fillCachePath:String{
        return TSFileManagerTool.cacheDirectory.appendingPathComponent(self).path
    }
    
    public var fillCacheURL:URL{
        return TSFileManagerTool.cacheDirectory.appendingPathComponent(self)
    }
    
    public var cachesLastURLString:String{
        let parts = self.components(separatedBy: "/Caches/")
        if let last = parts.last {
            return last
        }
        return self
    }
}
public extension String {
    
    public var isDocumentPath:Bool{
        return self.contains("/Documents/")
    }
    
    public var fillDocumentPath:String{
        return TSFileManagerTool.documentsDirectory.appendingPathComponent(self).path
    }
    
    public var fillDocumentURL:URL{
        return TSFileManagerTool.documentsDirectory.appendingPathComponent(self)
    }
    
    public var documentLastURLString:String{
        let parts = self.components(separatedBy: "/Documents/")
        if let last = parts.last {
            return last
        }
        return self
    }
}
